import json
import time

from fastapi import APIRouter
from re_common.baselibrary.tools.all_requests.aiohttp_request import AioHttpRequest
from re_common.baselibrary.tools.all_requests.mrequest import MRequest
from re_common.baselibrary.utils.core.mlamada import bools_string

from apps.allsubdb.wanfangjournal.models import WFQKDataRefModel, wfqk_headers, AZDownModel, ClassModel, \
    WFDownArticleModel
from apps.core.global_model import IdMarksModel, IdModel
from apps.core.m_route import ContextIncludedRoute
from apps.core.return_info import InputInfoModel, ReturnInfo

router = APIRouter(route_class=ContextIncludedRoute)


@router.post("/step1/get_all_class")
async def get_allclass(input: InputInfoModel[ClassModel]):
    """
    分类导航消失
    获取class分类 为使用分类下载期刊列表做准备;
    marks： clusterField;
    input.data.item == "0/" 时 获取的时上层分类的列表;
    获取某个大分类的小分类 可以获取上层分类后获取列表的name 然后将0替换成1;
    传入item
    :param input:
    :return:
    """
    return_info = ReturnInfo()
    url = r'https://c.wanfangdata.com.cn/Category/Facet/Magazine'
    this_header = wfqk_headers.copy()
    this_header["Host"] = "c.wanfangdata.com.cn"
    this_header["Origin"] = "https://c.wanfangdata.com.cn"
    item = input.data.item
    form = {
        "cluster_field": [{"field": "ClassCode", "prefix": item}]
    }
    proxy = input.proxy
    makrs = input.data.marks
    rrq = AioHttpRequest()
    rrq.set_url(url).set_data(json.dumps(form)) \
        .set_timeout(30).set_marks(makrs) \
        .set_proxy(proxy).set_header(this_header) \
        .set_middler_list(
        [rrq.status_code_middlerwares, rrq.is_json_middlerwares, rrq.marks_middlerwares])
    bools, dicts = await rrq.run(MRequest.POST)
    return_info.status = bools_string(bools)
    return_info.msg_code = dicts["code"]
    return_info.msg = dicts["msg"]
    return_info.data = {"html": rrq.html}
    return return_info.todict()


@router.post("/step1_a_z/wanfangqklist")
async def down_wanfangqklist(input: InputInfoModel[AZDownModel]):
    """
    以a到z 请求json 获取列表 a到z的下载通过传递 ch 和 page下载;
    pageNum 第一页时传1,makrs: total;
    使用class分类下载 传递 class_code 和 page下载;

    :param input:
    :return:
    """
    return_info = ReturnInfo()
    url = r'https://c.wanfangdata.com.cn/Category/Magazine/search'
    pageNum = input.data.pagenum
    ch = input.data.ch
    class_code = input.data.class_code
    if ch:
        pinyin_title = [ch]
    else:
        pinyin_title = []
    marks = input.data.marks
    proxy = input.proxy
    form = {
        "class_code": class_code,
        "core_periodical": [],
        "highlight_field": "",
        "pinyin_title": pinyin_title,
        "publish_status": "",
        "publishing_period": [],
        "query": [],
        "return_fields": [],
        "rows": 50,
        "sort_field": {"sort_field": "ImpactFactor"},
        "sponsor_region": [],
        "start": (pageNum - 1) * 50
    }
    this_header = wfqk_headers.copy()
    this_header['Host'] = 'c.wanfangdata.com.cn'
    this_header['Origin'] = 'https://c.wanfangdata.com.cn'

    rrq = AioHttpRequest()
    rrq.set_url(url).set_data(json.dumps(form)) \
        .set_timeout(30).set_marks(marks) \
        .set_proxy(proxy).set_header(this_header) \
        .set_middler_list(
        [rrq.status_code_middlerwares, rrq.is_json_middlerwares, rrq.marks_middlerwares])
    bools, dicts = await rrq.run(MRequest.POST)
    return_info.status = bools_string(bools)
    return_info.msg_code = dicts["code"]
    return_info.msg = dicts["msg"]
    return_info.data = {"html": rrq.html}
    return return_info.todict()


@router.post("/step2/down_information")
async def down_wanfangqklist(input: InputInfoModel[IdMarksModel]):
    """
    marks 建议为: perio_operation_wrap;
    id为pykm值;
    下载期刊的元数据信息，为期刊信息服务
    :param input:
    :return:
    """
    return_info = ReturnInfo()
    proxy = input.proxy
    pykm = input.data.id
    marks = input.data.marks
    url = "https://www.wanfangdata.com.cn/sns/third-web/per/perio/information?perioId={}"
    url = url.format(pykm)
    this_header = wfqk_headers.copy()
    this_header[
        "Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
    this_header["Referer"] = "http://www.wanfangdata.com.cn/sns/perio/{}".format(pykm)
    del this_header["Content-Type"]
    rrq = AioHttpRequest()
    rrq.set_url(url) \
        .set_timeout(30).set_marks(marks) \
        .set_proxy(proxy).set_header(this_header) \
        .set_middler_list(
        [rrq.status_code_middlerwares, rrq.marks_middlerwares])
    bools, dicts = await rrq.run(MRequest.GET)
    return_info.status = bools_string(bools)
    return_info.msg_code = dicts["code"]
    return_info.msg = dicts["msg"]
    return_info.data = {"html": rrq.html}
    return return_info.todict()


@router.post("/step2/down_synopsis")
async def down_synopsis(input: InputInfoModel[IdMarksModel]):
    """
    marks 建议为: perio_profile_info_left;
    id为pykm值;
    下载期刊的元数据信息，为期刊信息服务
    :param input:
    :return:
    """
    return_info = ReturnInfo()
    proxy = input.proxy
    pykm = input.data.id
    marks = input.data.marks
    url = "http://www.wanfangdata.com.cn/sns/third-web/per/perio/synopsis?perioId={}"
    url = url.format(pykm)
    this_header = wfqk_headers.copy()
    this_header[
        "Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
    this_header["Referer"] = "http://www.wanfangdata.com.cn/sns/perio/{}".format(pykm)
    rrq = AioHttpRequest()
    rrq.set_url(url) \
        .set_timeout(30).set_marks(marks) \
        .set_proxy(proxy).set_header(this_header) \
        .set_middler_list(
        [rrq.status_code_middlerwares, rrq.marks_middlerwares])
    bools, dicts = await rrq.run(MRequest.GET)
    return_info.status = bools_string(bools)
    return_info.msg_code = dicts["code"]
    return_info.msg = dicts["msg"]
    return_info.data = {"html": rrq.html}
    return return_info.todict()


@router.post("/step5/down_year_list")
async def down_synopsis(input: InputInfoModel[IdMarksModel]):
    """
    获取年 和期的json信息
    makrs： formalPublishes;
    :param input:
    :return:
    """
    url = "http://www.wanfangdata.com.cn/sns/third-web/per/perio/snsYearTree"
    return_info = ReturnInfo()
    proxy = input.proxy
    marks = input.data.marks
    pykm = input.data.id
    form = {
        "perioId": pykm
    }
    this_header = wfqk_headers.copy()
    this_header["Accept"] = "application/json, text/javascript, */*; q=0.01"
    this_header["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8"

    rrq = AioHttpRequest()
    rrq.set_url(url).set_data(form) \
        .set_timeout(30).set_marks(marks) \
        .set_proxy(proxy).set_header(this_header) \
        .set_middler_list(
        [rrq.status_code_middlerwares, rrq.is_json_middlerwares, rrq.marks_middlerwares])
    bools, dicts = await rrq.run(MRequest.POST)
    return_info.status = bools_string(bools)
    return_info.msg_code = dicts["code"]
    return_info.msg = dicts["msg"]
    return_info.data = {"html": rrq.html}
    return return_info.todict()


@router.post("/step7/down_issue")
async def down_synopsis(input: InputInfoModel[WFDownArticleModel]):
    """
    下载某一期 得到文章列表
    marks: totalRow;
    :param input:
    :return:
    """
    # 老的请求
    # url = r'http://www.wanfangdata.com.cn/perio/articleList.do'
    # form = {
    #     'page': str(page),
    #     'pageSize': '100',
    #     'issue_num': num,
    #     'publish_year': pubyear,
    #     'article_start': '',
    #     'article_end': str(time.localtime().tm_year),
    #     'title_article': '',
    #     'perio_id': pykm
    # }
    url = r'https://www.wanfangdata.com.cn/sns/third-web/per/perio/articleList'
    return_info = ReturnInfo()
    proxy = input.proxy
    marks = input.data.marks
    pykm = input.data.pykm
    page = input.data.page
    num = input.data.num
    try:
        num = int(num)
    except:
        pass
    pubyear = input.data.pubyear
    form = {
        'page': str(page),
        'pageSize': '100',
        'perioId': pykm,
        'title': '',
        'publishYear': str(pubyear),
        'issueNum': num,
        'otherYear': '',
    }
    this_header = wfqk_headers.copy()
    this_header["Accept"] = "application/json, text/javascript, */*; q=0.01"
    this_header["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8"
    rrq = AioHttpRequest()
    rrq.set_url(url).set_data(form) \
        .set_timeout(30).set_marks(marks) \
        .set_proxy(proxy).set_header(this_header) \
        .set_middler_list(
        [rrq.status_code_middlerwares, rrq.is_json_middlerwares, rrq.marks_middlerwares])
    bools, dicts = await rrq.run(MRequest.POST)
    return_info.status = bools_string(bools)
    return_info.msg_code = dicts["code"]
    return_info.msg = dicts["msg"]
    return_info.data = {"html": rrq.html}
    return return_info.todict()


@router.post("/step9/down_ref")
async def down_ref(input: InputInfoModel[WFQKDataRefModel]):
    """
    下载万方引文 ;
    ReferenceType 为 "Reference" 为引文; Quotation 为引证文献 <br>
    marks 建议为 "detail";
    :return:
    """
    return_info = ReturnInfo()
    marks = input.data.marks
    proxy = input.proxy
    this_header = wfqk_headers.copy()
    rawid = input.data.Id
    PageNum = input.data.PageNum
    ReferenceType = input.data.ReferenceType
    this_header['Referer'] = 'https://d.wanfangdata.com.cn/periodical/%s' % rawid
    this_header['Host'] = 'd.wanfangdata.com.cn'
    this_header['Origin'] = 'https://d.wanfangdata.com.cn'
    this_header['Accept'] = 'application/json, text/plain, */*'
    this_header['Content-Type'] = 'application/json;charset=UTF-8'
    data = {
        'ReferenceType': ReferenceType,
        'Id': rawid,
        'PageNum': PageNum
    }
    url = r'https://d.wanfangdata.com.cn/Detail/Reference'
    rrq = AioHttpRequest()
    rrq.set_header(this_header).set_url(url) \
        .set_timeout(30).set_marks(marks) \
        .set_proxy(proxy).set_data(json.dumps(data)) \
        .set_middler_list([rrq.status_code_middlerwares, rrq.marks_middlerwares, rrq.is_json_middlerwares])
    bools, dicts = await rrq.run(MRequest.POST)
    return_info.status = bools_string(bools)
    return_info.msg_code = dicts["code"]
    return_info.msg = dicts["msg"]
    return_info.data = {"html": rrq.html, "url": url}
    return return_info.todict()
